<template>
  <div>
    <div class="content">
      <input type="text" v-model="keyword" placeholder="输入你要搜索的城市">
    </div>
    <div class="search-content" v-show="keyword" ref="wrapper">
      <ul>
        <li @click="handleClick" class="item" v-for="(item,index) of list" :key="index">{{item.name}}</li>
        <li class="item" v-if="!list.length">没有更多的数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
import BScroll from "better-scroll";
export default {
  name: "CitySearch",
  props: ["cities"],
  methods:{
    handleClick(event){
      this.$store.commit("changeCity",event.target.innerText);
      this.$router.push("/") ;
      this.keyword = ""
    }
  },
  data() {
    return {
      keyword: "",
      /* 接受到能夠搜索到的數據 */
      list: []
    };
  },
  watch: {
    keyword() {
      if (!this.keyword) {
        this.list = [];
        return;
      }
      var result = [];
      for (var i in this.cities) {
        this.cities[i].forEach(ele => {
          if (
            ele.spell.startsWith(this.keyword) ||
            ele.name.startsWith(this.keyword)
          ) {
            result.push(ele);
          }
        });
      }
      this.list = result;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.scroll = new BScroll(this.$refs.wrapper, {});
    });
  }
};
</script>
<style lang="scss" scoped>
.content {
  position: fixed;
  width: 100%;
  top: 89px;
  height: 88px;
  display: flex;
  background: color(bg);
  align-items: center;
  justify-content: center;
  background: skyblue;
  padding: 1vw 1.333vw 2vw 0vw;
  z-index: 333;
  input {
    border: 1px solid #eee;
    border-radius: 15px;
    outline: none;
    font-size: 14px;
    height: 56px;
    width: 92%;
    padding-left: 12px;
  }
}
.search-content {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 176px;
  z-index: 400;
  overflow: hidden;
  background: #fff;
}
.item {
  line-height: 70px;
  border-bottom: 1px solid #eee;
  padding-left: 20px;
}
</style>
